package com.mars.pay.controller;

import com.mars.pay.entity.Order;
import com.mars.pay.service.OrderService;
import com.mars.pay.utils.QRCodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 聚合支付控制器
 * 支持微信和支付宝扫同一个二维码
 *
 * @author Mars
 */
@Slf4j
@Controller
@RequestMapping("/pay/union")
@RequiredArgsConstructor
public class UnionPayController {

    private final OrderService orderService;
    
    @Value("${app.base-url}")
    private String baseUrl;

    /**
     * 聚合支付页面
     * 显示二维码，支持微信和支付宝扫码
     */
    @GetMapping("/{orderId}")
    public String unionPay(@PathVariable Long orderId, Model model) {
        try {
            // 查询订单
            Order order = orderService.getByOrderId(orderId);
            if (order == null) {
                model.addAttribute("error", "订单不存在");
                return "error";
            }

            // 生成聚合支付中间页URL（从配置文件读取）
            String unionUrl = baseUrl + "/pay/union/redirect/" + orderId;
            
            // 生成二维码
            String qrCodeBase64 = QRCodeUtil.generateQRCodeBase64(unionUrl, 300, 300);

            // 传递数据到页面
            model.addAttribute("order", order);
            model.addAttribute("qrCode", qrCodeBase64);
            model.addAttribute("unionUrl", unionUrl);

            return "pay-union";
        } catch (Exception e) {
            log.error("聚合支付页面加载失败", e);
            model.addAttribute("error", "聚合支付页面加载失败：" + e.getMessage());
            return "error";
        }
    }

    /**
     * 聚合支付重定向页
     * 根据用户代理判断是微信还是支付宝，自动跳转
     */
    @GetMapping("/redirect/{orderId}")
    public String redirect(@PathVariable Long orderId, Model model) {
        // 查询订单
        Order order = orderService.getByOrderId(orderId);
        if (order == null) {
            model.addAttribute("error", "订单不存在");
            return "error";
        }

        model.addAttribute("orderId", orderId);
        return "pay-union-redirect";
    }
}

